package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.Code;
import com.itheima.domain.Result;
import com.itheima.domain.User;
import com.itheima.exception.BusinessException;
import com.itheima.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public Result findAll() {
        List<User> list = userService.findAll();
        return list!=null?new Result(Code.QUERY_OK,list):new Result(Code.QUERY_FAIL,"没有查询到数据");
    }

    @GetMapping("/{currentPage}/{pageSize}")
    public Result findByPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize) {
        PageInfo<User> pageInfo = userService.findByPage(currentPage, pageSize);
        return pageInfo!=null?new Result(Code.QUERY_OK,pageInfo):new Result(Code.QUERY_FAIL,"没有查询到数据");
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        User user = userService.findById(id);
        return user!=null?new Result(Code.QUERY_OK,user):new Result(Code.QUERY_FAIL,"没有查询到数据");

    }
    @PostMapping
    public Result save(@RequestBody User user, Errors errors){
        //获取异常信息
        if (errors.hasErrors()) {
            List<FieldError> fieldErrors = errors.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                //获取错误信息
                String message = fieldError.getDefaultMessage();
                //创建异常对象并抛出，那么ProjectExceptionAdvice会获取到异常信息
                /*BusinessException exception = new BusinessException(message);
                throw exception;*/

                throw new BusinessException(message);
            }

        }
        int count = userService.save(user);
        return count>0?new Result(Code.SAVE_OK,"保存成功"):new Result(Code.SAVE_FAIL,"保存失败");

    }

    @PutMapping
    public Result update(@RequestBody User user){
        int count = userService.update(user);
        return count>0?new Result(Code.UPDATE_OK,"修改成功"):new Result(Code.UPDATE_FAIL,"修改失败");
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        int count = userService.delete(id);
        return count>0?new Result(Code.DELETE_OK,"删除成功"):new Result(Code.DELETE_FAIL,"删除失败");
    }
    @PostMapping("/login")
    public Result login(String username, String password, HttpSession session){
        User user = userService.login(username, password);
        if (user!=null){
            session.setAttribute("user",user);
            return new Result(Code.LOGIN_OK,"登录成功");
        }else {
            return new Result(Code.LOGIN_FAIL,"登录失败");
        }
    }
}
